package com.ncloud.crm.dubboservice.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ncloud.aaaa.service.UserService;
import com.ncloud.chnl.service.CustUserService;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.PageHelperUtils;
import com.ncloud.crm.dubboservice.QueryInfoDubboService;
import com.ncloud.crm.entity.BsContract;
import com.ncloud.crm.entity.BsContractNode;
import com.ncloud.crm.entity.BsCust;
import com.ncloud.crm.entity.BsNode;
import com.ncloud.crm.entity.BsProjProd;
import com.ncloud.crm.entity.BsProject;
import com.ncloud.crm.entity.order.OrderCustomer;
import com.ncloud.crm.entity.order.OrderNode;
import com.ncloud.crm.entity.order.Work;
import com.ncloud.crm.mapper.BsContractMapper;
import com.ncloud.crm.mapper.BsCustMapper;
import com.ncloud.crm.mapper.BsNodeMapper;
import com.ncloud.crm.mapper.BsProjProdMapper;
import com.ncloud.crm.mapper.BsProjectMapper;
import com.ncloud.crm.mapper.OrderProjectMapper;
import com.ncloud.crm.mapper.WorkMapper;
import com.ncloud.crm.service.BsContractNodeService;
import com.ncloud.crm.service.BsNodeService;
import com.ncloud.crm.service.OrderCustomerService;
import com.ncloud.crm.utils.JsonUtil;


@Service
public class QueryInfoDubboServiceImpl implements QueryInfoDubboService {
    private static final org.apache.log4j.Logger logger = LogManager.getLogger(QueryInfoDubboServiceImpl.class);
	@Autowired
	private BsContractMapper contractMapper;
	@Autowired
	private BsCustMapper custMapper;
	@Autowired
	private BsNodeMapper nodeMapper;
	@Autowired
	private OrderProjectMapper orderProjectMapper;
	@Autowired
	private BsProjProdMapper bsProjProdMapper;
	@Autowired
	private BsContractNodeService bsContractNodeService;
	@Autowired
	private BsNodeService bsNodeService;
	@Autowired
	private BsProjectMapper bsProjectMapper;
	@Autowired
	private WorkMapper  workMapper;
	@Autowired
	private OrderCustomerService orderCustomerService;
	@Reference
	private UserService userService;
	@Reference
	private CustUserService custUserService;
	
	@Override
	public JSONArray getContractByProject(JSONObject json) {
		JSONArray contractArray = new JSONArray();
		if(json==null || !json.containsKey("userID")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}else{
			try {
				String manage = json.get("userID").toString();
				String projectId =json.get("projectId").toString();
				List<BsContract> listInfo = contractMapper.getBsContracts(projectId,manage);
				if(listInfo !=null){
					for(BsContract contract:listInfo){
						JSONObject contractObject = JSON.parseObject(JSON.toJSONString(contract));
						List<BsContract> childContracts = contractMapper.getBsContractsChild(projectId,manage,contract.getContractId());
						contractObject.put("subContracts",JSON.parseArray(JSON.toJSONString(childContracts)));
						contractArray.add(contractObject);
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}		
		}
		return contractArray;
	}
	
	@Override
	public JSONObject getCustByProject(JSONObject json) {
		BsCust bsCust = new BsCust();
		if(json==null || !json.containsKey("userID")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}else{
			try {
				String Manage = json.get("userID").toString();
				String ProjectId =json.get("projectId").toString();
				bsCust = custMapper.getBsCust(ProjectId,Manage);			
			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}		
		}
		return JSON.parseObject(JSON.toJSONString(bsCust));
	}
	

	@Override
	public Object getChannelCustByUser(JSONObject json) {
		List<BsCust> ListInfo = new ArrayList<BsCust>();
		Object object = null;
		PageInfo pageInfo =null;
		if(json==null || !json.containsKey("userID")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}else{
			try {
				String userID = json.get("userID").toString();
				if(PageHelperUtils.isPage(json)){
					PageHelperUtils.setPageParam(json);
					ListInfo = custMapper.getBsChannelCust(userID);
					pageInfo = new PageInfo(ListInfo);
					logger.debug("分页信息："+ JSON.toJSONString(pageInfo));
					object = JSON.parseObject(JSON.toJSONString(pageInfo));
				}else{
					ListInfo = custMapper.getBsChannelCust(userID);
					object = JSON.parseArray(JSON.toJSONString(ListInfo));
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}		
		}
		return object;
	}
	
	@Override
	public JSONArray getNodesByProject(JSONObject json) {
		List<BsNode> ListInfo = new ArrayList<BsNode>();
		if(json==null || !json.containsKey("userID")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}else{
			try {
				String Manage = json.get("userID").toString();
				String ProjectId =json.get("projectId").toString();
				ListInfo = nodeMapper.getBsNodes(ProjectId,Manage);			
			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}		
		}
		return JSON.parseArray(JSON.toJSONString(ListInfo));
	}
	
	@Override
	public JSONArray getSaleProject(JSONObject json) {		
		List<BsProject> ListInfo = new ArrayList<BsProject>();
		if(json==null || !json.containsKey("userID")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}else{
			try {
				String Manage = json.get("userID").toString();
				ListInfo = orderProjectMapper.getManager(Manage);			
			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}		
		}
		return JSON.parseArray(JSON.toJSONString(ListInfo));
	}

	@Override
	public JSONArray getProjProdByCustIdAndManager(JSONObject json) {
		List<BsProjProd> ListInfo = new ArrayList<BsProjProd>();
		if(json==null || !json.containsKey("userID") || !json.containsKey("custId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}else{
			try {
				String manager = json.get("userID").toString();
				String custId =json.get("custId").toString();
				ListInfo = bsProjProdMapper.getProjProdByCustIdAndManager(manager,custId);		
			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}		
		}
		return JSON.parseArray(JSON.toJSONString(ListInfo));
	}

	@Override
	public JSONArray getNodesByContract(JSONObject json) {
        logger.info("当前json对象="+json.toJSONString());
        if(!json.containsKey("contractInstId")){
			throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"contractInstId 不存在！");
		}
		//String contractId =json.getString("contractId");
		Long contractInstId = json.getLong("contractInstId");
		JSONArray array = new JSONArray();
		List<BsContractNode> bsContractNodes = bsContractNodeService.getNodesByContract(contractInstId);
		for (BsContractNode bsContractNode : bsContractNodes) {
			Long nodeId = bsContractNode.getNodeId();
			JSONObject nodeObject = bsNodeService.getNodeDetailInfo(nodeId);
			array.add(nodeObject);
		}
		return array;
	}

	@Override
	public JSONArray getProjectByCustIdAndManager(JSONObject json) {
		List<BsProject> ListInfo = new ArrayList<BsProject>();
		if(json==null || !json.containsKey("userID") || !json.containsKey("custId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}else{
			try {
				String manager = json.get("userID").toString();
				String custId =json.get("custId").toString();
				ListInfo = 	bsProjectMapper.getProjectByCustIdAndManager(custId, manager);	
			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}		
		}
		return JSON.parseArray(JSON.toJSONString(ListInfo));
	}

	@Override
	public JSONArray getWorksByContractInstId(JSONObject json) {
		List<Work> ListInfo = new ArrayList<Work>();
		if(json==null || !json.containsKey("contractInstId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}else{
			try {
				String contractInstId = json.get("contractInstId").toString();
				ListInfo = 	workMapper.getWorksByContractInstId(contractInstId);	
			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}		
		}
		return JSON.parseArray(JSON.toJSONString(ListInfo));
	}

	/*
	* 根据销售人员查询合同信息
	* */
	@Override
	public JSONArray getContractsBySaleOrUser(JSONObject json) {
		JSONArray contractArray = new JSONArray();
		if(!json.containsKey("flag") && StringUtils.isNotEmpty(json.getString("flag"))){
			throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"没有对应的查询类型flag,1:主合同，2：所有合同");
		}
		if(json==null || !json.containsKey("userID")){
			throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"销售人员id不存在！");
		}else{
			try {
				Long saleId = json.getLong("userID");

				if("1".equals(json.getString("flag"))){
					List<Map<String, Object>> listInfo = contractMapper.getBsContractsBySale(saleId);
					if(listInfo !=null){
						contractArray = JSON.parseArray(JsonUtil.toJson(listInfo));
					}
				}else if("2".equals(json.getString("flag"))) {
					List<Map<String, Object>> listInfo = contractMapper.getBsContractsAllBySale(saleId);
					if(listInfo !=null){
						contractArray = JSON.parseArray(JsonUtil.toJson(listInfo));
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
				throw new UserException(ResultEnum.DATABASE_ERROR);
			}
		}
		return contractArray;
	}

	/*
	* 根据销售人员查询项目信息
	* */


	/*
	* 根据父或子合同ID查询合同信息和对应子合同信息
	* */
    @Override
    public JSONObject getContractsByID(JSONObject json) {
        JSONObject contractObject = new JSONObject();
        if(json==null || !json.containsKey("contractId")){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"字段contractId不存在！传入父合同ID或子合同ID。");
        }else{
            try {
                Long contractId = json.getLong("contractId");
                BsContract bsContract = contractMapper.getBsContractsById(contractId);
                if(bsContract !=null){
                    contractObject = JSON.parseObject(JSON.toJSONString(bsContract));
                    List<BsContract> childContracts = contractMapper.getBsContractsChildById(bsContract.getContractId());
                    contractObject.put("subContracts",JSON.parseArray(JSON.toJSONString(childContracts)));
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new UserException(ResultEnum.DATABASE_ERROR);
            }
        }
        return contractObject;
    }


    /*
* 根据销售人员查询合同信息
* */
    @Override
    public JSONArray getProjectsBySaleOrUser(JSONObject json) {
        JSONArray contractArray = new JSONArray();
        if(json==null || !json.containsKey("userID")){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"销售人员id不存在！");
        }else{
            try {
                Long saleId = json.getLong("userID");
                List<Map<String, Object>> listInfo = bsProjectMapper.getBsProjectBySale(saleId);
                if(listInfo !=null && listInfo.size()>0){
                    contractArray = JSON.parseArray(JsonUtil.toJson(listInfo));
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new UserException(ResultEnum.DATABASE_ERROR);
            }
        }
        return contractArray;
    }
	/*根据邮箱查询是否存在账户*/
	@Override
	public JSONObject isExistsAccount(JSONObject json) {
    	JSONObject result = new JSONObject();
		if(json==null || !json.containsKey("contactEmail")){
			throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"客户联系人邮箱信息contactEmail不存在！");
		}else{
			Long id = userService.isUserAccount(json.getString("contactEmail"));
			if(id == null){
				List<OrderCustomer> list = orderCustomerService.getCustByEmail(json.getString("contactEmail"));
				if(list != null && list.size()>0){
					result.put("flag",true);
				}else{
					result.put("flag",false);
				}
			}else{
				result.put("flag",true);
			}
		}
		logger.info("账户唯一性结果："+result.toJSONString());
		return result;
	}

	@Override
	public JSONArray getNodesByUser(JSONObject json) {
		//通过userId获得对应custId
		Long custId = custUserService.getCustByUserId(json);
		json.put("custId", custId);
		json.put("type", "0");
		return getNodesByCust(json);
	}
	
	/*根据客户查询对应的节点信息*/
	@Override
	public JSONArray getNodesByCust(JSONObject json) {
		JSONArray result = new JSONArray();
		if(json==null || !json.containsKey("custId")){
			throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"客户id信息不存在custId！");
		}
		if(!json.containsKey("type")){
			throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"请输入查询类型type【0:查询节点信息，1：查询节点详细信息】");
		}
		if("0".equals(json.getString("type"))){
			List<BsNode> list = bsNodeService.getNodesByCust(json.getLong("custId"));
			result = JSON.parseArray(JSON.toJSONString(list));
		}else if("1".equals(json.getString("type"))){
			List<BsNode> list = bsNodeService.getNodesByCust(json.getLong("custId"));
			if(list !=null){
				for(BsNode node:list){
					JSONObject nodeDetail = bsNodeService.getNodeDetailInfo(node.getNodeId());
					result.add(nodeDetail);
				}
			}
		}
		return result;
	}
	
	/*根据订单查询对应的节点信息*/
	@Override
	public JSONArray getNodesByOrder(JSONObject json) {
		JSONArray result = new JSONArray();
		if(json==null || !json.containsKey("orderId")){
			throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"订单id信息不存在orderId！");
		}
		if(!json.containsKey("type")){
			throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"请输入查询类型type【0:查询订单工单信息，1：查询订单节点详细信息】");
		}
		if("0".equals(json.getString("type"))){
			List<OrderNode> list = bsNodeService.getBsNodesByOrder(json.getLong("orderId"));
			result = JSON.parseArray(JSON.toJSONString(list));
		}else if("1".equals(json.getString("type"))){
			List<OrderNode> list = bsNodeService.getBsNodesByOrder(json.getLong("orderId"));
			if(list !=null){
				for(OrderNode node:list){
					if(node.getOrderState().equals("3")){
						JSONObject nodeDetail = bsNodeService.getBsNodeDetailInfo(node);
						result.add(nodeDetail);
					}else{
					JSONObject nodeDetail = bsNodeService.getBsONodeDetailInfo(node);
					result.add(nodeDetail);
					}
				}
			}
		}
		return result;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Object getCustList(JSONObject json) {
		Object object = null;
		PageInfo pageInfo =null;
		if(PageHelperUtils.isPage(json)){
			PageHelperUtils.setPageParam(json);
			List<BsCust> bsCusts = custMapper.getBsCustList();
			pageInfo = new PageInfo(bsCusts);
			object = JSON.parseObject(JSON.toJSONString(pageInfo));
		}else {
			List<BsCust> bsCusts = custMapper.getBsCustList();
			object = JSON.parseArray(JSON.toJSONString(bsCusts));
		}
		return object;
	}

	@Override
	public JSONObject getCustInfoByUser(JSONObject json) {
		Long custId = custUserService.getCustByUserId(json);
		BsCust bsCust = custMapper.getCustInfoById(custId);
		if(bsCust==null){
			JSONObject cust = orderCustomerService.getCustInfoByCustId(custId);
			return cust;
		}
		return JSON.parseObject(JSON.toJSONString(bsCust));
	}

	/*根据客户和武汉节点code查询设备节点的位置信息*/

	@Override
	public JSONObject getNodePosition(JSONObject json) {
		JSONObject result = new JSONObject();
		if(!json.containsKey("custId")){
			throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"客户信息custId不存在！");
		}
		if(!json.containsKey("nodeCode")){
			throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"对方的的设备编码必传nodeCode！");
		}
		result = bsNodeService.getNodeMapInfoByCode(json.getString("nodeCode"),json.getLong("custId"));
		logger.info("节点位置信息："+result.toJSONString());
		return result;
	}
}
